package com.yinlei.appserver

import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException

class MainActivity : AppCompatActivity() {

    private lateinit var shs: SimpleHttpServer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val wc = WebConfiguration(8088,50)
        shs = SimpleHttpServer(wc)
        shs.registerResourceHandler(ResourceInAssetsHandler(this))
        shs.registerResourceHandler(object : UploadImageHandler() {
            override fun onImageLoaded(path: String) {
                super.onImageLoaded(path)
                showImage(path)
            }
        })
        shs.startAsync()
    }

    private fun showImage(path: String) {
        runOnUiThread {
            val bitmap = BitmapFactory.decodeFile(path)
            myImg.setImageBitmap(bitmap)
            Toast.makeText(this@MainActivity, "Image showed!", Toast.LENGTH_SHORT).show()
        }
    }



    override fun onDestroy() {
        try {
            shs.stopAsync()
        } catch (e: IOException) {
            Log.e("yinlei",e.toString())
        }
        super.onDestroy()
    }
}
